const app = getApp()
const netRequest = require("../../utils/requestUtil.js")

Page({
  data: {
    items: [],
    placeholder: "输入要搜索的内容",
    page: 1,
    isNewestArticlesLoading: false
  },
  //事件处理函数
  bindViewTap: function (event) {

    var postId = event.currentTarget.dataset.articleId;

    var item = this.data.items[event.currentTarget.dataset.itemIndex];
    wx.navigateTo({
      url: '/pages/article_content/article_content?postId=' + postId + '&title=' + item.title + '&cover=' + item.thumb_url,
    })
  },
  onLoad: function () {

    this.refreshData()
  },

  refreshData: function () {
    var that = this;
    if (that.data.isNewestArticlesLoading) {
      return;
    }
    that.showLoadingDialog();
    that.data.isNewestArticlesLoading = true;

    netRequest({
      url: "/article/newest",
      data: { page: 1 },
      success: function (res) {

        that.setData({ items: res.data, page: res.current_page });
      },
      fail: function () { },
      complete: function () {
        that.data.isNewestArticlesLoading = false;

        wx.hideNavigationBarLoading(); //完成停止加载
        wx.stopPullDownRefresh(); //停止下拉刷新
      
        that.hideLoadingDialog();
      }

    });

  },

  showLoadingDialog: function () {
    wx.showLoading({
      title: '加载中...',
    });
  },
  hideLoadingDialog: function () {
    wx.hideLoading();
  },

  onPullDownRefresh: function () {
    var self = this;
    self.refreshData();
  },
  onReachBottom: function () {
    var that = this;

    if (that.data.isNewestArticlesLoading) {
      return;
    }

    that.showLoadingDialog();
    that.data.isNewestArticlesLoading = true;
    var page = that.data.page + 1;

    var currentItems = this.data.items;
    netRequest({
      url: "/article/newest",
      data: { page: page },
      success: function (res) {
        console.log(res.current_page);


        var items = that.data.items.concat(res.data);
        that.setData({ items: items, page: res.current_page });
      },
      fail: function () { },
      complete: function () {
        that.data.isNewestArticlesLoading = false;

        wx.hideNavigationBarLoading(); //完成停止加载
        wx.stopPullDownRefresh(); //停止下拉刷新

        that.hideLoadingDialog();
      }
    });


  }

})
